﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Mime;
using System.Net.Mail;
using System.Text;

using Fuse8.DomainFramework.Common;

namespace Fuse8.ContentManagementFramework.SystemFacade.Common
{
    public static class EmailSender
    {
        public static void SendMessage(string from, IEnumerable<string> to, string subject, string body)
        {
            SendMessage(from, to, string.Empty, subject, body, null);
        }

        public static void SendMessage(string from, string to, string subject, string body)
        {
            SendMessage(from, to, string.Empty, subject, body, null);
        }

        public static void SendMessage(string from, string to, string bcc, string subject, string body, IList<string> files)
        {
            SendMessage(from, new[] { to }, bcc, subject, body, files);
        }

        public static void SendMessage(string from, IEnumerable<string> to, string bcc, string subject, string body, IList<string> files)
        {
            Guard.ArgumentNotEmpty(from, "from");
            Guard.ArgumentNotEmpty(to as ICollection, "to");
            Guard.ArgumentNotEmpty(subject, "subject");
            Guard.ArgumentNotEmpty(body, "body");

            var message = new MailMessage();

            message.From = new MailAddress(from);

            foreach (var recipient in to)
            {
                if (!string.IsNullOrEmpty(recipient))
                    message.To.Add(new MailAddress(recipient));
            }

            if (!string.IsNullOrEmpty(bcc))
            {
                message.Bcc.Add(new MailAddress(bcc));
            }
            message.Subject = subject;
            message.Body = body;
            message.Priority = MailPriority.Normal;
            message.BodyEncoding = Encoding.UTF8;
            message.IsBodyHtml = true;

            if ((files != null) && (files.Count > 0))
            {
                foreach (var item in files)
                {
                    var contentType = new ContentType();

                    contentType.MediaType = MediaTypeNames.Application.Octet;
                    contentType.Name = item;

                    message.Attachments.Add(new Attachment(item, contentType));
                }
            }

            var client = new SmtpClient();

            client.Send(message);
        }
    }
}
